package br.com.light.adapter.retorno.lote.ws;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.DOMOutputter;

import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.StreamTransformationException;

public class MappingRetornoLoteWS implements StreamTransformation {
	
	

	public static void main(String[] args) throws FileNotFoundException, StreamTransformationException {
		File file = new File("D:/documentos/Complex/Light/schema/LoteRPS/Retorno/RetornoLoteRPSWS.xml");
		InputStream in = new FileInputStream(file);
			
		File fileOut = new File("D:/documentos/Complex/Light/schema/LoteRPS/Retorno/RetornoLoteRPS.xml");
		OutputStream out = new FileOutputStream(fileOut);
		
		new MappingRetornoLoteWS().execute(in, out);

	}
	
	public void setParameter(Map objParam) {
		

	}
	

	public void execute(InputStream in, OutputStream out)
			throws StreamTransformationException {
		
		try {

		
		Reader reader = new BufferedReader(new InputStreamReader(in, "ISO-8859-1"));
	    StringBuffer content = new StringBuffer();
	    char[] buffer = new char[1024];
	    int n;
	     
	    while ( ( n = reader.read(buffer)) != -1 ) {
	        content.append(buffer,0,n);
	    }
	    
	    String retorno = content.toString();
	    
	    int x = retorno.indexOf("<RetornoXML>");
	    
	    int j = retorno.indexOf("</RetornoXML>");
	    
		String xmlPI = retorno.substring(x+12, j).trim();
		
		String nfeProcStr = xmlPI.replaceAll( "&#62;", ">" ).
				  replaceAll("&#60;", "<" );
	    
		int k = nfeProcStr.indexOf("?>");
		String xmlFinal = nfeProcStr.substring(k+2);
		
		InputStream inWS = new ByteArrayInputStream(xmlFinal.getBytes());
		
		
		//Criando estrutura para SP
		Element header = new Element("RetornoEnvioLoteRPS", "ns0", "http://www.prefeitura.sp.gov.br/nfe");
		
		Element cabecalho = new Element("Cabecalho");
		cabecalho.setAttribute("Versao", "1");
		header.addContent(cabecalho);

		
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(inWS);
		Element root = doc.getRootElement();
		List elements = root.getChildren();
		Iterator iter = elements.iterator();
	    
		
		while (iter.hasNext()) {
			Element elem = (Element) iter.next();
			
			
			if("Cabecalho".equals(elem.getName())){
				Element sucesso = new Element("Sucesso");
				cabecalho.addContent(sucesso);
				String sucessoIn = elem.getChildText("Sucesso");
				sucesso.setText(sucessoIn);
				
				List listCabecalho = elem.getChildren();
				Iterator iterCabecalho = listCabecalho.iterator();
				while(iterCabecalho.hasNext()){
					Element elemCabecalho = (Element)iterCabecalho.next();
				
					if("InformacoesLote".equals(elemCabecalho.getName())){
						Element informacoesLote = new Element("InformacoesLote");
						cabecalho.addContent(informacoesLote);
						List listInfoLote = elemCabecalho.getChildren();
						Iterator iterInfoLote = listInfoLote.iterator();
						while(iterInfoLote.hasNext()){
							Element elemInfoLote = (Element)iterInfoLote.next();
							if("NumeroLote".equals(elemInfoLote.getName())){
								Element numeroLote = new Element("NumeroLote");
								informacoesLote.addContent(numeroLote);
								numeroLote.setText(elemCabecalho.getChildText("NumeroLote"));
								continue;
							}
							if("InscricaoPrestador".equals(elemInfoLote.getName())){
								Element inscricaoPrestador = new Element("InscricaoPrestador");
								informacoesLote.addContent(inscricaoPrestador);
								inscricaoPrestador.setText(elemCabecalho.getChildText("InscricaoPrestador"));
								continue;
							}
							if("CPFCNPJRemetente".equals(elemInfoLote.getName())){
								Element cpfCnpjRemente = new Element("CPFCNPJRemetente");
								informacoesLote.addContent(cpfCnpjRemente);
								List listCpfCNPJ = elemInfoLote.getChildren();
								Iterator iterCpfCNPJ = listCpfCNPJ.iterator();
								while(iterCpfCNPJ.hasNext()){
									Element elemCpfCnpj = (Element)iterCpfCNPJ.next();
									if("CNPJ".equals(elemCpfCnpj.getName())){
										Element cnpj = new Element("CNPJ");
										cpfCnpjRemente.addContent(cnpj);
										cnpj.setText(elemInfoLote.getChildText("CNPJ"));
										continue;
									}
								}
								
							}
							if("DataEnvioLote".equals(elemInfoLote.getName())){
								Element dataEnvioLote = new Element("DataEnvioLote");
								informacoesLote.addContent(dataEnvioLote);
								dataEnvioLote.setText(elemCabecalho.getChildText("DataEnvioLote"));
								continue;
							}
							if("QtdNotasProcessadas".equals(elemInfoLote.getName())){
								Element qtdNotasProcessadas = new Element("QtdNotasProcessadas");
								informacoesLote.addContent(qtdNotasProcessadas);
								qtdNotasProcessadas.setText(elemCabecalho.getChildText("QtdNotasProcessadas"));
								continue;
							}
							if("TempoProcessamento".equals(elemInfoLote.getName())){
								Element tempoProcessamento = new Element("TempoProcessamento");
								informacoesLote.addContent(tempoProcessamento);
								tempoProcessamento.setText(elemCabecalho.getChildText("TempoProcessamento"));
								continue;
							}
							if("ValorTotalServicos".equals(elemInfoLote.getName())){
								Element valorTotalServicos = new Element("ValorTotalServicos");
								informacoesLote.addContent(valorTotalServicos);
								valorTotalServicos.setText(elemCabecalho.getChildText("ValorTotalServicos"));
								continue;
							}
							if("ValorTotalDeducoes".equals(elemInfoLote.getName())){
								Element valorTotalDeducoes = new Element("ValorTotalDeducoes");
								informacoesLote.addContent(valorTotalDeducoes);
								valorTotalDeducoes.setText(elemCabecalho.getChildText("ValorTotalDeducoes"));
								continue;
							}
						}
					}
					
				}
				
				
				continue;
			}
			if("Alerta".equals(elem.getName())){
				
				Element alerta = new Element("Alerta");
				header.addContent(alerta);
				Element codigoAlerta = new Element("Codigo");
				alerta.addContent(codigoAlerta);
				Element descricao = new Element("Descricao");
				alerta.addContent(descricao);
				
				String codigoAlertaIn = elem.getChildText("Codigo");
				codigoAlerta.setText(codigoAlertaIn);
				
				String descricaoAlertaIn = elem.getChildText("Descricao");
				descricao.setText(descricaoAlertaIn);
				
				List listAlertaChavesRPS = elem.getChildren();
				Iterator alertChaveRPSIter = listAlertaChavesRPS.iterator();
				while (alertChaveRPSIter.hasNext()) {
					Element alertChaveRPSElement = (Element) alertChaveRPSIter.next();
					if("ChaveRPS".equals(alertChaveRPSElement.getName())){
						
						Element chaveRPSAlerta = new Element("ChaveRPS");
						alerta.addContent(chaveRPSAlerta);
						Element inscPrestAlerta = new Element("InscricaoPrestador");
						chaveRPSAlerta.addContent(inscPrestAlerta);
						Element serieRPSAlerta = new Element("SerieRPS");
						chaveRPSAlerta.addContent(serieRPSAlerta);
						Element numRPSAlerta = new Element("NumeroRPS");
						chaveRPSAlerta.addContent(numRPSAlerta);
						
						
						String inscPrestAlertaRPSIn = alertChaveRPSElement.getChildText("InscricaoPrestador");
						inscPrestAlerta.setText(inscPrestAlertaRPSIn) ;
						
						String serieRPSAlertaIn = alertChaveRPSElement.getChildText("SerieRPS");
						serieRPSAlerta.setText(serieRPSAlertaIn);
						
						String numeroRPSAlertaIn = alertChaveRPSElement.getChildText("NumeroRPS");
						numRPSAlerta.setText(numeroRPSAlertaIn);
					}

					if("ChaveNFe".equals(alertChaveRPSElement.getName())){
						
						Element chaveNFEAlerta = new Element("ChaveNFe");
						alerta.addContent(chaveNFEAlerta);
						Element inscPrestChaveNfeAlerta = new Element("InscricaoPrestador");
						chaveNFEAlerta.addContent(inscPrestChaveNfeAlerta);
						Element numNfeAlerta = new Element("NumeroNfe");
						chaveNFEAlerta.addContent(numNfeAlerta);
						Element codVeriAlerta = new Element("CodigoVerificacao");
						chaveNFEAlerta.addContent(codVeriAlerta);
						String inscPrestNfeAlertaIn = alertChaveRPSElement.getChildText("InscricaoPrestador");
						inscPrestChaveNfeAlerta.setText(inscPrestNfeAlertaIn);
					
						String numeroNfeAlertaIn = alertChaveRPSElement.getChildText("NumeroNfe");
						numNfeAlerta.setText(numeroNfeAlertaIn);
						
						String codigoVerificacaoAlertaIn = alertChaveRPSElement.getChildText("CodigoVerificacao");
						codVeriAlerta.setText(codigoVerificacaoAlertaIn);
						
					}
					
				}
			}
			
			if("Erro".equals(elem.getName())){
				Element erro = new Element("Erro");
				header.addContent(erro);
				Element codigoErro = new Element("Codigo");
				erro.addContent(codigoErro);
				Element descricaoErro = new Element("Descricao");
				erro.addContent(descricaoErro);
				
				String codigoErroIn = elem.getChildText("Codigo");
				codigoErro.setText(codigoErroIn);
				
				String descricaoErroIn = elem.getChildText("Descricao");
				descricaoErro.setText(descricaoErroIn);
				
				List listAlertaChavesRPS = elem.getChildren();
				Iterator alertChaveRPSIter = listAlertaChavesRPS.iterator();
				while (alertChaveRPSIter.hasNext()) {
					Element alertChaveRPSElement = (Element) alertChaveRPSIter.next();
					if("ChaveRPS".equals(alertChaveRPSElement.getName())){
						Element chaveRPSErro = new Element("ChaveRPS");
						erro.addContent(chaveRPSErro);
						Element inscPrestErro = new Element("InscricaoPrestador");
						chaveRPSErro.addContent(inscPrestErro);
						Element serieRPSErro  = new Element("SerieRPS");
						chaveRPSErro.addContent(serieRPSErro);
						Element numRPSErro = new Element("NumeroRPS");
						chaveRPSErro.addContent(numRPSErro);
						String inscPrestRPSErroIn = alertChaveRPSElement.getChildText("InscricaoPrestador");
						inscPrestErro.setText(inscPrestRPSErroIn);
						
						String serieRPSErroIn = alertChaveRPSElement.getChildText("SerieRPS");
						serieRPSErro.setText(serieRPSErroIn);
							
						String numeroRPSErroIn = alertChaveRPSElement.getChildText("NumeroRPS");
						numRPSErro.setText(numeroRPSErroIn);
						
					}
					if("ChaveNFe".equals(alertChaveRPSElement.getName())){
						Element chaveNFEErro = new Element("ChaveNFe");
						erro.addContent(chaveNFEErro);
						Element inscPrestChaveNfeErro = new Element("InscricaoPrestador");
						chaveNFEErro.addContent(inscPrestChaveNfeErro);
						Element numNfeErro = new Element("NumeroNfe");
						chaveNFEErro.addContent(numNfeErro);
						Element codVerifErro = new Element("CodigoVerificacao");
						chaveNFEErro.addContent(codVerifErro);
						
						String inscPrestNfeErroIn = alertChaveRPSElement.getChildText("InscricaoPrestador");
						inscPrestChaveNfeErro.setText(inscPrestNfeErroIn);

						String numeroNfeErroIn = alertChaveRPSElement.getChildText("NumeroNfe");
						numNfeErro.setText(numeroNfeErroIn);

						String codigoVerificacaoNfeErroIn = alertChaveRPSElement.getChildText("CodigoVerificacao");
						codVerifErro.setText(codigoVerificacaoNfeErroIn);
						
					}
					
				}
			}
			if("ChaveNFeRPS".equals(elem.getName())){
				Element chaveNfeRPS = new Element("ChaveNFeRPS");
				List chaves = elem.getChildren();
				Iterator chavesIter = chaves.iterator();
				while (chavesIter.hasNext()) {
					Element chaveElem = (Element) chavesIter.next();
					if("ChaveNFe".equals(chaveElem.getName())){
						header.addContent(chaveNfeRPS);
						Element chaveNfe = new Element("ChaveNFe");
						chaveNfeRPS.addContent(chaveNfe);
						Element inscPrestNfe = new Element("InscricaoPrestador");
						chaveNfe.addContent(inscPrestNfe);
						Element numNFeNfe = new Element("NumeroNFe");
						chaveNfe.addContent(numNFeNfe);
						Element codVerifNfe = new Element("CodigoVerificacao");
						chaveNfe.addContent(codVerifNfe);
						String inscPrestNfeIn = chaveElem.getChildText("InscricaoPrestador");
						inscPrestNfe.setText(inscPrestNfeIn);
		
						String numNfeIn = chaveElem.getChildText("NumeroNFe");
						numNFeNfe.setText(numNfeIn);
						
						String codVerifNfeIn = chaveElem.getChildText("CodigoVerificacao");
						codVerifNfe.setText(codVerifNfeIn);

					}
					
					if("ChaveRPS".equals(chaveElem.getName())){		
						Element chaveRPS = new Element("ChaveRPS");
						chaveNfeRPS.addContent(chaveRPS);
						Element inscPrestChave = new Element("InscricaoPrestador");
						chaveRPS.addContent(inscPrestChave);
						Element serieRPSChave = new Element("SerieRPS");
						chaveRPS.addContent(serieRPSChave);
						Element numRPSChave = new Element("NumeroRPS");
						chaveRPS.addContent(numRPSChave);
						String inscPrestRPSIn = chaveElem.getChildText("InscricaoPrestador");
						inscPrestChave.setText(inscPrestRPSIn);
						
						String serieRPSIn = chaveElem.getChildText("SerieRPS");
						serieRPSChave.setText(serieRPSIn);
						
						
						String numRpsIn = chaveElem.getChildText("NumeroRPS");
						numRPSChave.setText(numRpsIn);
						
					}
					
				}
				
			}

		}
	
		Document jdoc = new Document(header);
		
		DOMOutputter outputter = new DOMOutputter();
		org.w3c.dom.Document docNative = outputter.output(jdoc);
		
		TransformerFactory tf=TransformerFactory.newInstance();
		Transformer transform=tf.newTransformer();
		
		transform.transform(new DOMSource(docNative), new StreamResult(out));

	    
	    
	    
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}


}
